<?php

namespace app\admin\controller\haipi;

use app\common\controller\Backend;
use app\common\library\utils\RandomUtils;
use app\common\model\haipi\Ticket as TicketModel;
use app\common\model\haipi\TicketToken;

/**
 * 卡密管理
 */
class Ticket extends Backend
{
    /**
     * Ticket模型对象
     * @var object
     * @phpstan-var \app\common\model\haipi\Ticket
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new TicketModel();
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

     public function gen(){
        $number = $this->request->post('number');
        $id = $this->request->post('id');
        if(empty($number) || empty($id)){
            $this->error('缺少参数');
        }
        $ticket = TicketModel::where('id', $id)->field('id, price')->find();
        if(empty($ticket)){
            $this->error("票据不存在");
        }
        $number = $number > 1000 ? 1000 : $number;
        $tokens = [];
        while($number){
            $tokens[] = [
                'token' => RandomUtils::generateUniqueRandom(),
                'price' => $ticket['price'],
                'ticket_id' => $id,
            ];
            $number -= 1;
        }
        TicketToken::insertAll($tokens);
        $this->success('生成成功');
     }
}